// #ifdef H5
import * as jWeixin from 'weixin-js-sdk'
import { showError, getCurrentPage, buildUrL } from '@/core/app'
import { isWeixinOfficial } from '@/core/platform'
import wxofficialApi from '@/api/wxofficial'
import StoreModel from '@/common/model/Store'
import WxofficialSettingModel from '@/common/model/wxofficial/Setting'

// 标记已注入微信jssdk (用于确保全局仅注入一次)
let configState = false

// 注入微信jssdk配置信息
const setConfig = async () => {
  if (configState) {
    return
  }
  // 获取当前页面url (不包含#及其后面部分)
  const url = window.location.href.split('#')[0]
  // 请求后端获取jssdkConfig
  const response = await wxofficialApi.jssdkConfig(url)
  // 注入配置信息
  jWeixin.config(response.data.config)
  configState = true
  // 提示错误
  jWeixin.error(res => {
    console.error('jWeixin.error', res)
    showError(`微信链接分享配置错误：${res.errMsg}`)
  })
}

// 设置分享卡片的内容
const updateShareData = async (shareData) => {
  // 是否开启微信公众号链接分享卡片
  const enabled = await WxofficialSettingModel.isWxofficialLinkShareCard()
  if (!isWeixinOfficial || !enabled) {
    return
  }
  // 整理分享数据
  // const shareData = { title, desc, link, imgUrl }
  // shareData.link = shareData.link || window.location.href
  shareData.link = await getShareUrl()

  setConfig()
  jWeixin.ready(() => {
    console.log('jWeixin.ready', shareData)
    jWeixin.updateAppMessageShareData(shareData)
    jWeixin.updateTimelineShareData(shareData)
    // jWeixin.onMenuShareAppMessage(shareData)
    // jWeixin.onMenuShareTimeline(shareData)
  })
}

// 获取分享链接 (H5外链)
const getShareUrl = async () => {
  const { path, query } = getCurrentPage()
  return new Promise((resolve, reject) => {
    // 获取h5站点地址
    StoreModel.h5Url().then(baseUrl => {
      // 生成完整的分享链接
      const shareUrl = buildUrL(baseUrl, path, query)
      resolve(shareUrl)
    })
  })
}

/**
 * 选择微信收货地址
 * Doc: https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/JS-SDK.html
 */
const openAddress = () => {
  return new Promise((resolve, reject) => {
    console.log('openAddress')
    setConfig()
    jWeixin.ready(() => {
      jWeixin.openAddress({
        success(res) {
          // mix: countryName文档里写的是国家, 实际是区县
          res.countyName = res.countryName
          resolve(res)
        }
      })
    })
  })
}

export default {
  updateShareData,
  openAddress
}
// #endif